package com.richfun.boot.common.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * HTTP 请求工具
 * */
public class HttpClientUtil {
    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
    /**
     * 发送HTTP POST 请求
     * @param url 请求地址
     * @param params 请求参数
     * */
    public static void sendPostRequest(String url, Map<String,Object> params) {
        logger.info("==== HTTP POST 请求数据 开始 ====");
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type","application/json;charset=utf-8");
        httpPost.setHeader("Accept","application/json");
        httpPost.setEntity(new StringEntity(JSONObject.toJSONString(params),"utf-8"));
        try {
            // 发送 HTTP 请求
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity= httpResponse.getEntity();
            String result = "";
            if (httpEntity != null) {
                // 获取响应数据
                result = EntityUtils.toString(httpEntity,"utf-8");
            }
            logger.info("==== HTTP POST 请求数据 成功 ====");
            logger.info("==== HTTP POST 响应数据 :  ====\n" + result);
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("==== HTTP POST 请求数据 失败 ====");
        } finally {
            //关闭连接
            httpPost.releaseConnection();
        }
    }

    /**
     * 发送HTTP GET 请求
     * */
    public static String sendGetRequest(String url, Map<String,Object> params) {
        logger.info("==== HTTP GET 请求数据 开始 ====");
        HttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(getParamsUrl(url, params));
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity= httpResponse.getEntity();
            String result = "";
            if (httpEntity != null) {
                result = EntityUtils.toString(httpEntity,"utf-8");
            }
            logger.info("==== HTTP GET 请求数据 成功 ====");
            logger.info("==== HTTP GET 响应数据 :  ====\n"+result);
            return result;
        } catch (IOException e) {
            e.printStackTrace();
            logger.info("==== HTTP GET 请求数据 失败 ====");
        } finally {
            httpGet.releaseConnection();
        }
        return null;
    }

    /**
     * 组合带参GET请求链接
     * */
    private static String getParamsUrl(String url, Map<String,Object> params) {
        if (params == null || params.isEmpty()) {
            return url;
        }
        StringBuilder paramsStr = new StringBuilder(url + "?");
        Set<String> keys = params.keySet();
        for (String key : keys) {
            paramsStr.append(key).append("=").append(params.get(key)).append("&");
        }
        String paramsUrl = paramsStr.substring(0, paramsStr.length()-1);
        logger.info("HTTP GET 请求URL: " + paramsUrl);
        return paramsUrl;
    }


    public static void main(String[] args) {
        String url = "http://701b50ff.ngrok.io/cloud/wx/sendServiceWxMsg.html";
        Map<String,Object> params = new HashMap<>();
        params.put("service_id", 779);
        params.put("state", "开始服务");
        params.put("remarkToWaiter", "湖南省东悦企业管理咨询有限责任公司人事服务FW779开始服务, 请注意查看.");
        sendPostRequest(url, params);
    }




}
